<template>
  <!--图片上传-->
  <div>
    <div v-show='isRemoved' class="pic_upload">
      <!-- :format="['jpg', 'jpeg', 'png']"-->
      <Upload
        ref="upload"
        :class="type+'Class'"
        :show-upload-list="false"
        :type="type"
        :headers="headers"
        :accept="handleFormat(format)"
        :format="format"
        :on-success="handleSuccess"
        :on-format-error="handleError"
        :before-upload="beforeUpload"
        :on-progress="handleProgress"
        :on-exceeded-size="handleExceeded"
        :disabled="disabled"
        :max-size="maxSize"
        :action="baseUrl + '/support/file/upload'"
        style="display: inline-block;float: left;width: 90px;">
        <!-- 默认样式 -->
        <div v-if="type === 'select'">
          <a :style="{cursor: disabled?'not-allowed':'pointer'}" v-show="!disabled">上传附件</a>
          <div class="loader" v-show="disabled"></div>
        </div>
        <!-- drag样式 -->
        <div v-if="type === 'drag'" class="drag-upload">
          <div class="content-top">
            <div class="top-img"></div>
            <div class="top-text">
              <p><i class="tip-number">1</i><i class="tip-click">点击 </i>选择文件上传</p>
              <p><i class="tip-number">2</i>将文件拖拽到这里上传</p>
            </div>
          </div>
<!--          <p class="center-bottom">支持扩展名：{{ '.'+format.join(' .')}}</p>-->
          <p class="center-bottom">支持扩展名：png, jpg, doc, docx, xlsx</p>
        </div>
      </Upload>
    </div>
    <div>
      <ul class="ivu-upload-list">
        <li
          class="ivu-upload-list-file ivu-upload-list-file-finish"
          v-for="(item, index) in urlPaths"
          :key="index"
          @click.stop="downLoad(item)">
          <span
            ><i
              :class="[
                'ivu-icon',
                sliceString(item.extension)
              ]"
            ></i>
            {{ item.imgName }}
          </span>
          <i v-if="type=== 'drag'" @click.stop="handleRemove(item)" class="drag-delete">删除</i>
          <i
            class="ivu-icon ivu-icon-ios-close ivu-upload-list-remove"
            v-show="isRemoved && type === 'select'"
            @click.stop="handleRemove(item)"
          ></i>
        </li>
      </ul>
    </div>
    <Modal :title="previewImg.imgName" v-model="visible" style="z-index:10000">
      <img :src="previewImg.imgUrl" v-if="visible" style="width: 100%" />
    </Modal>
  </div>
</template>

<script>
import uploadPhoto from "./uploadPhoto";
import renderUrl from "@/api/apiHost";
export default {
  props: {
    maxLength: {
      //最大上传数
      type: Number,
      default: 5
    },
    isRemoved:{
      type:Boolean,
      default:true
    },
    maxSize: {
      //最大上传大小
      type: Number,
      default: 20480
    },
    imgLists: {
      type: Array, // { imgUrl: url, imgName: name }
      default: () => []
    },
    format: {
      type: Array,
      default: ()=>{return ['png', 'jpg', 'jpeg', 'pdf', 'doc', 'docx', 'xlsx', 'xls']}
    },
    type: {
      type: String,
      default: 'select'
    },
  },
  data() {
    return {
      previewImg: {},
      visible: false,
      headers: { Authorization: this.$cookie.get("access_token") },
      Lists: [],
      urlPaths: [],
      deleteIds: [],
      baseUrl: renderUrl("utiltools"),
      disabled: false,
      percent: 0,
      imgUrl: "" //新增是不能调用接口 需要获取本地文件地址
    };
  },
  computed: {},
  created() {},
  mounted() {
    this.uploadList = this.$refs.upload.fileList;
  },
  watch: {
    imgLists: {
      handler(val) {
        if (this.imgLists&&this.imgLists.length > 0) {
          console.log(val,"img")
          this.imgLists.forEach(item => {
            this.initImg(item, false);
          });
          console.log(this.imgLists,"this.imgLists")
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    /**
     *  @param {Object} fileInfo 查看或上传时传入的文件参数
     *  @param {Bollean} isUpload 是查看还是上传 true为上传 false为查看
     * 图片处理
     */
    async initImg(fileInfo, isUpload) {
      if (isUpload) {
        this.percent = 0;
        this.disabled = false;
        this.$emit("uploading",this.disabled)
        let arr = fileInfo.fileName.split(".");
        let extension = arr[arr.length - 1];
        this.urlPaths.push({
          imgUrl: this.imgUrl,
          url: fileInfo.fileUrl,
          imgName: fileInfo.fileName,
          newFileName: fileInfo.newFileName,
          extension: extension
        });
        this.$emit(
          "uploadSuccess",
          this.urlPaths,
          this.deleteIds
        );
      } else {
        await fetch(
          renderUrl("utiltools") +
            "/support/file/download?fileUrl=" +
            (fileInfo.url || fileInfo.fileUrl),
          {
            method: "get",
            headers: {
              "Content-type": "application/json",
              Authorization: this.$cookie.get("access_token")
            }
          }
        )
          .then(response => response.blob())
          .then(blob => {
            var url = window.URL.createObjectURL(blob);
            this.percent = 0;
            this.disabled = false;
            this.$emit("uploading",!this.disabled)
            this.urlPaths.push({
              imgUrl: url,
              url: fileInfo.fileUrl || fileInfo.url,
              imgName: fileInfo.fileName || fileInfo.attachmentName,
              newFileName: fileInfo.newFileName,
              extension: fileInfo.attachmentExtension,
              attachmentId: fileInfo.attachmentId
            });
          });
      }
    },
    /**
     * 文件图标filter
     */
    sliceString(extension, type = this.type) {
      if (type === 'select') {
        if (['jpg','jpeg','gif','png'].includes(extension)) return 'ivu-icon-ios-image';
        return 'ivu-icon-md-document'
      }
      if (type === 'drag') {
        let mapObj = { png: 'PNG',jpg: 'JPG',jpeg: 'JPEG',
          pdf: 'PDF',doc: 'DOC',docx: 'DOC',xlsx: 'XLS',xls: 'XLS'}
          return 'darg-icon darg-'+mapObj[extension]
      }
    },
    handleSuccess(res, file, fileList) {
      console.log(this.urlPaths, "urlPaths");
      if (res.code === 200) {
        this.initImg(res.result, true);
      } else {
        this.disabled = false;
        this.$emit("uploading",!this.disabled)
        this.$Message.error(res.message);
      }
    },
    handleFormat(arr) {
      return arr.map(item=>'.'+item).join(',')
    },
    /**
     * 删除图片
     */
    // itemphoto(data) {
    //   let index = this.Lists.findIndex(item => {
    //     return item.imgUrl === data.imgUrl;
    //   });

    //   if (this.Lists[index] && this.Lists[index].attachmentId) {
    //     this.deleteIds.push(this.Lists[index].attachmentId);
    //   }

    //   this.Lists.splice(index, 1);
    //   this.$emit("uploadSuccess", this.urlPaths, this.deleteIds);
    // },
    /**
     * 删除文件
     */
    handleRemove(file) {
      let index = this.urlPaths.findIndex(item => {
        return item.imgUrl === file.imgUrl;
      });
      if (file.attachmentId) {
        this.deleteIds.push(file.attachmentId);
      }
      this.urlPaths.splice(index, 1);
      this.$emit("uploadSuccess", this.urlPaths, this.deleteIds);
    },
    /**
     * 下载文件
     */
    downLoad(file) {
      if (
        file.extension === "jpg" ||
        file.extension === "jpeg" ||
        file.extension === "gif" ||
        file.extension === "png"
      ) {
        console.log(file, "file");
        this.previewImg = file;
        this.visible = true;
      } else {
        const a = document.createElement("a");
        a.style.display = "none";
        a.download = file.imgName;
        a.href = file.imgUrl;
        a.click();
      }
    },
    /**
     * 清空
     */
    resetImg() {
      this.Lists = [];
      this.urlPaths = [];
      this.imgUrl = "";
    },
    /**
     * 格式错误回调
     */
    handleError() {
      // this.$Message.error("上传图片格式不正确,请选择'jpg', 'jpeg', 'png'格式的图片");
     const formatstr = this.format.join(",")
      this.disabled = false;
      this.$emit("uploading",this.disabled)
      this.$Message.error(
        "上传格式不正确,请选择"+formatstr+"等格式"
      );
    },
    /**
     * 超出指定大小
     */
    handleExceeded(file) {
      this.disabled = false;
      this.$emit("uploading",this.disabled)
      return this.$Message.error("上传文件最大大小为" + this.maxSize + "kb");
    },
    /**
     *
     */
    beforeUpload(file) {
      if ([...this.Lists, ...this.urlPaths].length >= this.maxLength) {
        this.$Message.warning("最多上传" + this.maxLength + "个");
        return false;
      }
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const _base64 = reader.result;
        this.imgUrl = _base64; //将_base64赋值给图片的src，实现图片预览
      };
      this.disabled = true;
      this.$emit("uploading",this.disabled)
    },
    /**
     * 上传中
     */
    handleProgress(event, file, fileList) {
      this.percent = event.percent;
      // if(event.percent===100){
      //   this.disabled = false
      //   this.percent = 0
      // }
    }
  },
  components: {
    uploadPhoto
  }
};
</script>

<style scoped lang="scss">
.pic_upload {
  overflow: hidden;
}
.pic_upload_list {
  width: 70%;
  height: 90px;
  line-height: 90px;
  margin-left: 30px;
  float: left;
  background-color: white;
  // display: inline-block;
  // border: 1px solid #bbbbbb;
  border-radius: 2px;
  /*overflow-y: scroll;*/
}
.ivu-upload-list {
  > li {
    // float:  left;
  }
}
.loader {
    display: inline-block;
    width: 2em;
    height: 2em;
    color: inherit;
    vertical-align: middle;
    pointer-events: none;
    border: .2em solid transparent;
    border-top-color: currentcolor;
    border-radius: 50%;
    -webkit-animation: 1s loader linear infinite;
    animation: 1s loader linear infinite;
    position: relative;
}
.loader:before {
    content: '';
    display: block;
    width: inherit;
    height: inherit;
    position: absolute;
    top: -.2em;
    left: -.2em;
    border: .2em solid currentcolor;
    border-radius: 50%;
    opacity: .5;
}
@-webkit-keyframes loader {
    0% {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
    }
    100% {
        -webkit-transform: rotate(360deg);
        transform: rotate(360deg);
    }
}
@keyframes loader {
    0% {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
    }
    100% {
        -webkit-transform: rotate(360deg);
        transform: rotate(360deg);
    }
}
// 拖拽附件样式
/deep/.ivu-upload.dragClass {
  width: 100% !important;
}
// 拖拽-文件图标
/deep/.darg-DOC { background: url('~@/assets/img/uploadImg/DOC.png') no-repeat center; }
/deep/.darg-JPEG { background: url('~@/assets/img/uploadImg/JPEG.png') no-repeat center; }
/deep/.darg-JPG { background: url('~@/assets/img/uploadImg/JPG.png') no-repeat center; }
/deep/.darg-PDF { background: url('~@/assets/img/uploadImg/PDF.png') no-repeat center; }
/deep/.darg-PNG { background: url('~@/assets/img/uploadImg/PNG.png') no-repeat center; }
/deep/.darg-TXT { background: url('~@/assets/img/uploadImg/TXT.png') no-repeat center; }
/deep/.darg-XLS { background: url('~@/assets/img/uploadImg/XLS.png') no-repeat center; }
.darg-icon {
  background-size: 100% 100%;
  width: 16px;
  height: 16px;
}
/deep/.drag-delete {
  float: right;
  padding-right: 10px;
  font-style: normal;
  color: red;
  &:hover {
    cursor: pointer;
    color: red;
  }
}
.drag-upload {
  padding: 10px;
  .content-top {
    display: flex;
    min-height: 160px;
    .top-img {
      flex: 1;
      background: url('~@/assets/img/uploadImg/JPG.png') no-repeat center;
    }
    .top-text {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
      i {
        font-style: normal;
      }
      p {
        .tip-number {
          color: #fff;
          width: 16px;
          height: 16px;
          background-color: #0994fd;
          border-radius: 50%;
          display: inline-block;
          line-height: 16px;
          padding-right: 5p;
          margin-right: 10px;
        }
        .tip-click {
          color: rgb(9, 148, 253);
        }
      }
    }
  }
  .center-bottom {
    float: left;
  }
}
</style>
